package yunquan.wang.base.spring.security;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

public class SecurityMetadataSourceAuthImpl implements
		FilterInvocationSecurityMetadataSource {

	private Set<ConfigAttribute> authSet = new HashSet<ConfigAttribute>();

	@Override
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		final HttpServletRequest request = ((FilterInvocation) object)
				.getRequest();
		/**
		 * 一个地址，就为唯一权限。所有的地址，都在权限保护范围内。即，默认所有的URL都需要授权
		 * 
		 */
		String requestpath = getRequestPath(request);
 		String auth = requestpath.replace("/", "_").toUpperCase().substring(1);
		ConfigAttribute security = new SecurityConfig(auth);
		return Arrays.asList(security);
	}

	private String getRequestPath(HttpServletRequest request) {
		String url = request.getServletPath();
		if (request.getPathInfo() != null) {
			url += request.getPathInfo();
		}
//		url = url.toLowerCase();
//		if(url.contains("."))
//		{
//			url=url.substring(1, url.lastIndexOf("."));
//		}
		return url;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
//		if (authSet.size() == 0) {
//			List<Authority> authList = authorityService.findAll();
//			for (Authority auth : authList) {
//				authSet.add(new SecurityConfig(auth.getName()));
//			}
//		}
		return authSet;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

}
